(function($){

var defaultOptions = {
    values: ['saw', 'sine', 'triangle', 'square'],
    changeToNextDistance: 50,
    defaultValue: 'sine',
    onchange: function(){}
};

$.fn.knob2 = function(options){
    var _t = this;
    options = $.extend({}, defaultOptions, options);
    //当前值
    var value;
    var $rotatable = this.find('.rotatable');
        if($rotatable.length === 0) $rotatable = this;

    function getValueByDistance(end){
        var dx       = end.left - start.left;
        var dy       = end.top - start.top;
        var distance = Math.sqrt(dx * dx + dy * dy);
        var step     = Math.round(distance / options.changeToNextDistance);
        var isPlus   = dx > dy;
        var index    = options.values.indexOf(valueWhenDrag) + 100 * options.values.length;
            index    = isPlus ? index + step : index - step;
            index    = index % options.values.length;
        return options.values[index];
    }

    var start, valueWhenDrag;
    this.draggable({
        helper: function(){
            return $('<div>');
        },
        start: function(e, params){
            valueWhenDrag = value;
            start = params.position;
        },
        drag: function(e, params){
            var _value = getValueByDistance(params.position);
            _t.setValue(_value);
        },
        stop: function(e, params){
            var _value = getValueByDistance(params.position);
            _t.setValue(_value);
        }
    });
    this.setValue = function(val){
        if(val === value) return;
        value = val;
        options.onchange(value);
        _t.attr('type', value);
    };
    this.getValue = function(){
        return value;
    };

    requestAnimationFrame(function(){
        _t.setValue(options.defaultValue);
    });
    return this;
};

})(jQuery);